package com.lysj.bhp.api.controller;

import com.lysj.bhp.api.base.ApiContent;
import com.lysj.bhp.investment.domain.Reward;
import com.lysj.bhp.system.domain.Verify;
import com.lysj.bhp.system.domain.VerifyEmail;
import com.lysj.bhp.system.repository.VerifyEmailRepository;
import com.lysj.bhp.util.random.RandomUtil;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import com.lysj.bhp.wallet.domain.*;
import com.lysj.bhp.wallet.vo.WalletVo;
import com.lysj.bhp.withdraw.domain.WithDrawAddress;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;

@RestController
@RequestMapping("/api/v2/user")
@Api(value = "ApiWithdrawAddressController", tags = "提币地址模块接口")
public class ApiWithdrawAddressController extends ApiContent {


    private final long NEXT_SEND_EMAIL = 1000 * 60 * 3;// 发送邮件间隔(3分钟)

    /**
     * @author drj
     * @date 2018/05/25 15:45
     * @Description:显示用户所有提币地址
     */
    @ApiOperation(value = "我的提币地址", notes = "需要钱包类型,type 10:比特币;20:以太坊;100:BHPC;30:比特币钻石;40:布比币;")
    @GetMapping("/show_address")
    public List<WithDrawAddress> showAddress() {
        List<WithDrawAddress> withDrawAddressList = withDrawAddressRepository.findByUserIdAndStatus(currentUser().getUserId(), 1);
        return withDrawAddressList;
    }


    /**
     * @author drj
     * @date 2018/05/25 15:52
     * @Description:添加提币地址
     */
    @ApiOperation(value = "添加提币地址", notes = "需要地址标签,地址,邮箱验证,钱包类型,type 10:比特币;20:以太坊;100:BHPC;30:比特币钻石;40:布比币;")
    @PostMapping("/add_address")
    public Resp addAddress(String addressLabel, String address, int type, String verify) {
        Verify verifyQuery = verifyRepository.findOne(currentUser().getEmail());
        if (verifyQuery == null) {
            return new Resp(Resp.PARAM_ERROR, "验证码错误");
        }
        if (!verify.equalsIgnoreCase(verifyQuery.getVerify())) {
            return new Resp(Resp.PARAM_ERROR, "验证码错误");
        }
        if (ParamUtil.isBlack(addressLabel)) {
            return new Resp(Resp.PARAM_ERROR, "标签不能为空");
        }
        if (ParamUtil.isBlack(address)) {
            return new Resp(Resp.PARAM_ERROR, "地址不能为空");
        }
        //判定用户添加的提币地址是否大于5
        List<WithDrawAddress> queryWithDrawAddressList = withDrawAddressRepository.findByUserIdAndTypeAndStatus(currentUser().getUserId(), type, 1);
        if (queryWithDrawAddressList.size() >= 5) {
            return new Resp(Resp.PARAM_ERROR, "钱包最大提币地址为5个");
        }

        //查询该用户相对应的币种的提币地址是否重复
        List<WithDrawAddress> withDrawAddressList = withDrawAddressRepository.findByAddressAndUserIdAndTypeAndStatus(address, currentUser().getUserId(), type, 1);
        if (withDrawAddressList.size() > 0) {
            return new Resp(Resp.PARAM_ERROR, "该币种的地址已存在,请勿重复添加");
        }
        WithDrawAddress withDrawAddress = new WithDrawAddress();
        withDrawAddress.setUserId(currentUser().getUserId());
        withDrawAddress.setType(type);
        withDrawAddress.setAddress(address);
        withDrawAddress.setAddressLabel(addressLabel);
        withDrawAddress.setStatus(1);//正常状态
        withDrawAddress.setAuthentication("已认证");
        withDrawAddress.setDefaultStatus(1); //非默认地址
        withDrawAddressRepository.save(withDrawAddress);
        return new Resp("添加成功");
    }


    /**
     * @author drj
     * @date 2018/05/25 15:46
     * @Description:删除提币地址
     */
    @ApiOperation(value = "删除提币地址", notes = "需要提币地址id")
    @PostMapping("/remove_address")
    public Resp removeAddress(Long withDrawAddressId) {
        if (ParamUtil.isBlack(withDrawAddressId)) {
            return new Resp(Resp.PARAM_ERROR, "请选择提币地址");
        }
        WithDrawAddress withDrawAddress = withDrawAddressRepository.findOne(withDrawAddressId);
        withDrawAddress.setStatus(2);
        withDrawAddressRepository.save(withDrawAddress);
        return new Resp("删除成功");
    }

    @ApiOperation(value = "显示单个钱包提币地址", notes = "需要钱包类型type10:比特币;20:以太坊;100:BHPC")
    @PostMapping("/show_wallet_address")
    public Resp showWalletAddress(int type) {
        Map<String, Object> map = new HashMap<>();
        List<WithDrawAddress> withDrawAddressList = new ArrayList<>();
        if (ParamUtil.isBlack(type)) {
            return new Resp(Resp.PARAM_ERROR, "系统错误");
        }
        withDrawAddressList = withDrawAddressRepository.findByUserIdAndTypeAndStatus(currentUser().getUserId(), type, 1);
        map.put("withDrawAddress", withDrawAddressList);
        return new Resp(map);
    }

    @ApiOperation(value = "获取提币邮箱验证码")
    @PostMapping("/fetch_withdraw_email_verify_code")
    public Resp fetchWithdrawEmailVerifyCode() {
        Verify verifyQuery = verifyRepository.findOne(currentUser().getEmail());
           // 若存在历史记录且还在拦截器内,则拦截
        if (null != verifyQuery && verifyQuery.getNextSendEmailMs() > System.currentTimeMillis()) {
            return new Resp(Resp.PARAM_ERROR, "您的操作太频繁,请稍后再进行操作");
        }
        verifyQuery = new Verify();
        verifyQuery.setEmail(currentUser().getEmail());
        verifyQuery.setExpires(System.currentTimeMillis() + verifyRepository.EXPIRE);
        verifyQuery.setNextSendEmailMs(System.currentTimeMillis() + NEXT_SEND_EMAIL);
        verifyQuery.setVerify(RandomUtil.getRandomString(5));

        boolean result = mailService.sendVerifyCodeHtmlMail(currentUser().getEmail(), verifyQuery.getVerify());
        if (!result) {
            return new Resp(Resp.PARAM_ERROR, "邮件发送失败,请重试");
        }
        verifyRepository.save(verifyQuery);
        return new Resp("获取验证码成功，请登陆您的邮箱查看");
    }

    @ApiOperation(value = "地址管理", notes = "显示用户钱包信息,默认显示该用户的比特币提币地址")
    @GetMapping("/address_manage")
    public Resp wallteList() {
        Map<String, Object> map = new HashMap<>();
        //获取用户的所有钱包
        BitCoinWallet bitCoinWallet = bitcoinWalletRepository.findByUserId(currentUser().getUserId());
        EthereumWallet ethereumWallet = ethereumWalletRepository.findByUserId(currentUser().getUserId());
        BhpcWallet bhpcWallet = bhpcWalletRepository.findByUserId(currentUser().getUserId());
        DiamondBitcoinWallet diamondBitcoinWallet = diamondBitcoinWalletRepository.findByUserId(currentUser().getUserId());
        BuWallet buWallet = buWalletRepository.findByUserId(currentUser().getUserId());
        //创建返回的钱包
        List<WalletVo> walletVos = new LinkedList<>();
        WalletVo bitcoinWallteVo = new WalletVo();
        WalletVo ethereumWalletVo = new WalletVo();
        WalletVo bhpcWalletVo = new WalletVo();
        WalletVo diamondBitcoinWalletVo = new WalletVo();
        WalletVo buWalletVo = new WalletVo();
        bitcoinWallteVo.setType(10);
        bitcoinWallteVo.setName("BTC");
        bitcoinWallteVo.setChineseName("比特币");
        ethereumWalletVo.setType(20);
        ethereumWalletVo.setName("ETH");
        ethereumWalletVo.setChineseName("以太坊");
        bhpcWalletVo.setType(100);
        bhpcWalletVo.setName("BHPC");
        bhpcWalletVo.setChineseName("算力现金");
        diamondBitcoinWalletVo.setType(30);
        diamondBitcoinWalletVo.setName("BCD");
        diamondBitcoinWalletVo.setChineseName("比特钻石");
        buWalletVo.setType(40);
        buWalletVo.setName("BU");
        buWalletVo.setChineseName("布");
        if (null != bitCoinWallet) {
            bitcoinWallteVo.setTotalBalance(bitCoinWallet.getBalance().setScale(6, BigDecimal.ROUND_DOWN));
            bitcoinWallteVo.setAvailBalance(bitCoinWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
            bitcoinWallteVo.setFreezeBalance(bitCoinWallet.getFreezeBalance().setScale(6, BigDecimal.ROUND_DOWN));
            bitcoinWallteVo.setRewardBalance(new BigDecimal(BigInteger.ZERO));
        } else {
            bitcoinWallteVo.setTotalBalance(new BigDecimal(BigInteger.ZERO));
            bitcoinWallteVo.setAvailBalance(new BigDecimal(BigInteger.ZERO));
            bitcoinWallteVo.setFreezeBalance(new BigDecimal(BigInteger.ZERO));
            bitcoinWallteVo.setRewardBalance(new BigDecimal(BigInteger.ZERO));
        }
        if (null != ethereumWallet) {
            ethereumWalletVo.setTotalBalance(ethereumWallet.getBalance().setScale(6, BigDecimal.ROUND_DOWN));
            ethereumWalletVo.setAvailBalance(ethereumWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
            ethereumWalletVo.setFreezeBalance(ethereumWallet.getFreezeBalance().setScale(6, BigDecimal.ROUND_DOWN));
            ethereumWalletVo.setRewardBalance(new BigDecimal(BigInteger.ZERO));
        } else {
            ethereumWalletVo.setTotalBalance(new BigDecimal(BigInteger.ZERO));
            ethereumWalletVo.setAvailBalance(new BigDecimal(BigInteger.ZERO));
            ethereumWalletVo.setFreezeBalance(new BigDecimal(BigInteger.ZERO));
            ethereumWalletVo.setRewardBalance(new BigDecimal(BigInteger.ZERO));
        }
        if (null != bhpcWallet) {
            bhpcWalletVo.setTotalBalance(bhpcWallet.getBalance().setScale(6, BigDecimal.ROUND_DOWN));
            bhpcWalletVo.setAvailBalance(bhpcWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
            bhpcWalletVo.setFreezeBalance(bhpcWallet.getFreezeBalance().setScale(6, BigDecimal.ROUND_DOWN));
            bhpcWalletVo.setRewardBalance(new BigDecimal(BigInteger.ZERO));
        } else {
            bhpcWalletVo.setTotalBalance(new BigDecimal(BigInteger.ZERO));
            bhpcWalletVo.setAvailBalance(new BigDecimal(BigInteger.ZERO));
            bhpcWalletVo.setFreezeBalance(new BigDecimal(BigInteger.ZERO));
            bhpcWalletVo.setRewardBalance(new BigDecimal(BigInteger.ZERO));
        }
        if (null != diamondBitcoinWallet) {
            diamondBitcoinWalletVo.setTotalBalance(diamondBitcoinWallet.getBalance().setScale(6, BigDecimal.ROUND_DOWN));
            diamondBitcoinWalletVo.setAvailBalance(diamondBitcoinWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
            diamondBitcoinWalletVo.setFreezeBalance(diamondBitcoinWallet.getFreezeBalance().setScale(6, BigDecimal.ROUND_DOWN));
            diamondBitcoinWalletVo.setRewardBalance(new BigDecimal(BigInteger.ZERO));
        } else {
            diamondBitcoinWalletVo.setTotalBalance(new BigDecimal(BigInteger.ZERO));
            diamondBitcoinWalletVo.setAvailBalance(new BigDecimal(BigInteger.ZERO));
            diamondBitcoinWalletVo.setFreezeBalance(new BigDecimal(BigInteger.ZERO));
            diamondBitcoinWalletVo.setRewardBalance(new BigDecimal(BigInteger.ZERO));
        }
        if (null != buWallet) {
            buWalletVo.setTotalBalance(buWallet.getBalance().setScale(6, BigDecimal.ROUND_DOWN));
            buWalletVo.setAvailBalance(buWallet.getAvailBalance().setScale(6, BigDecimal.ROUND_DOWN));
            buWalletVo.setFreezeBalance(buWallet.getFreezeBalance().setScale(6, BigDecimal.ROUND_DOWN));
            buWalletVo.setRewardBalance(new BigDecimal(BigInteger.ZERO));
        } else {
            buWalletVo.setTotalBalance(new BigDecimal(BigInteger.ZERO));
            buWalletVo.setAvailBalance(new BigDecimal(BigInteger.ZERO));
            buWalletVo.setFreezeBalance(new BigDecimal(BigInteger.ZERO));
            buWalletVo.setRewardBalance(new BigDecimal(BigInteger.ZERO));
        }
        walletVos.add(bitcoinWallteVo);
        walletVos.add(ethereumWalletVo);
        walletVos.add(bhpcWalletVo);
        walletVos.add(diamondBitcoinWalletVo);
        walletVos.add(buWalletVo);
        map.put("walletVos", walletVos);
        List<WithDrawAddress> withDrawAddressList = withDrawAddressRepository.findByUserIdAndTypeAndStatus(currentUser().getUserId(), 10, 1);
        map.put("withDrawAddressList", withDrawAddressList);
        return new Resp(map);
    }

}
